package org.demo.io.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;


public class HttpHandler extends ChannelInboundHandlerAdapter {
    private  static Logger logger = LoggerFactory.getLogger(HttpHandler.class);


    public void channelReadCompleta(ChannelHandlerContext ctx){
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        try {
            FullHttpRequest fullHttpRequest=(FullHttpRequest) msg;
            String url = fullHttpRequest.uri();
            if (url.contains("/test"))
                handleTest(fullHttpRequest,ctx,"hello, this is a demo!");
            else
                handleTest(fullHttpRequest,ctx,"others");
        }catch (Exception e){
            logger.error(e+"");
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    public void handleTest(FullHttpRequest fullHttpRequest,ChannelHandlerContext ctx,String msg){
        FullHttpResponse response = null;
        try {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(msg.getBytes(StandardCharsets.UTF_8)));
            response.headers().set("Content-Type","application/json");
            response.headers().set("Content-Length",response.content().readableBytes());
        } catch (Exception e){
            logger.error("system is error:"+e);
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.NO_CONTENT);
        } finally {
            if (fullHttpRequest !=null){
               if (!HttpUtil.isKeepAlive(fullHttpRequest)){
                   ctx.write(response).addListener(ChannelFutureListener.CLOSE);
               } else {
                   response.headers().set(CONNECTION,KEEP_ALIVE);
                   ctx.write(response);
               }
            }
        }

    }

}
